/*
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 */

package com.wttech.dzzf.process.service.migrate;

import com.wtkj.vo.dzzf.base.kfwd.FundAccount;
import com.wttech.dzzf.process.dao.CbcBankDataCheckDao;
import com.wttech.dzzf.process.dao.TransferUserInfoDao;
import com.wttech.dzzf.process.model.FundTemp;
import com.wttech.dzzf.process.service.base.BaseInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

import static com.wttech.dzzf.process.constant.UserConstants.DEFAULT_PROCESS_NUM;

/**
 * 工行、建行历史数据导入服务实现
 *
 * @author MaShibo
 * @date 2017/12/10.
 */
@Service
public class ImportHisDataService {

	private static final Logger LOGGER = LoggerFactory.getLogger(ImportHisDataService.class);

	@Resource(name = "fundAccountHisDataProcess")
	private FundAccountProcessService fundAccountProcessService;

	@Resource
	private CbcBankDataCheckDao cbcBankDataCheckDao;

	@Resource
	private BaseInfoService baseInfoService;

	@Resource
	private ThreadPoolTaskExecutor executor;

	private void process() {
		int total = cbcBankDataCheckDao.queryFundAccountNum();
		LOGGER.info("共{}条数据待检测", total);
		int count = (int) Math.ceil((double) total / DEFAULT_PROCESS_NUM);
		LOGGER.info("共需要处理{}次", count);
		List<Future<Void>> futures = new ArrayList<>(count);
		for (int i = 0; i < count; i++) {
			int num = i + 1;
			futures.add(executor.submit(() -> processOnce(num)));
		}
		baseInfoService.getFutureResult(futures);
		LOGGER.info("执行完毕");
		executor.shutdown();
	}

	private Void processOnce(int num) {
		LOGGER.info("第{}次开始执行", num);
		int startRow = (num - 1) * DEFAULT_PROCESS_NUM + 1;
		int endRow = num * DEFAULT_PROCESS_NUM;
		List<FundAccount> fundAccounts = cbcBankDataCheckDao.queryPageFundAccountInfos(startRow, endRow);
		fundAccounts.forEach(this::processFundAccount);
		LOGGER.info("第{}次结束执行", num);
		return null;
	}

	private void processFundAccount(FundAccount fundAccount) {
		try {
			fundAccountProcessService.process(fundAccount);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			createErrorRecord(fundAccount.getFundAccountId());
		}
	}

	private void createErrorRecord(String fundAccountId) {
		baseInfoService.createFailtureId(fundAccountId);
	}

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		ImportHisDataService service = context.getBean(ImportHisDataService.class);
		service.process();
	}

}
